package com.legendframework.dao.yaml.support;

import com.legendframework.dao.support.ClassUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: ShallowDream7
 * @Date: 2019/8/10 13:20
 * @Description:
 */
public class BaseDynamicYml<T> implements IBaseDynamicYml<T> {

    private String path;

    private Class<T> typeClass;

    Map<String, IBaseYml<T>> map = new HashMap<>();

    public BaseDynamicYml(String path,Class<T> typeClass) {
        this.path = path.endsWith("/") ? path : path + "/";
        this.typeClass = typeClass;
    }


    @Override
    public IBaseYml<T> get(String id) {
        IBaseYml<T> yml = map.get(id);
        if(yml == null){
            yml = new BaseYml<>(StringUtils.join(path,id,".yml"),typeClass);
            map.put(id,yml);
        }
        return yml;
    }

    @Override
    public List<IBaseYml<T>> getAll() {
        if (map.isEmpty()) {
            //读取目录下的所有文件
            File file = new File(path);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            List<IBaseYml<T>> ymls = findFile(file);
            for (IBaseYml<T> yml : ymls) {
                map.put(String.valueOf(ClassUtils.getIdByEntity(yml.get())),yml);
            }
        }
        return new ArrayList<>(map.values());
    }

    /**
     * 递归获取目录下的所有yml文件
     * @param file 文件目录
     * @return
     */
    private List<IBaseYml<T>> findFile(File file){
        List<IBaseYml<T>> ymls = new ArrayList<>();
        File[] files = file.listFiles();
        if (files == null) {
            return new ArrayList<>();
        }
        for (File listFile : files) {
            if (listFile.isDirectory()) {
                ymls.addAll(findFile(listFile));
            }else {
                String[] split = listFile.getName().split("\\.");
                if (!"yml".equals(split[split.length - 1])) {
                    continue;
                }
                ymls.add(new BaseYml<>(listFile.getAbsolutePath(),typeClass));
            }
        }
        return ymls;
    }
}



